package org.example.common.configs.permission;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.common.configs.exception.ServiceException;
import org.example.common.configs.log.LogInterceptor;
import org.example.common.utils.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author weigang
 * @create 2022-10-31 11:15
 */

@Aspect
@Component
public class PermissionAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(PermissionAspect.class);

    @Before("execution(public * org.example.controller..*.*(..))")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = IPUtils.getIpAddr(request);
        if (StrUtil.isBlank(ip)) {
            ip = "127.0.0.1";
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Permission permission = AnnotationUtils.findAnnotation(method, Permission.class);
        PermissionIgnore premissionIgnore = AnnotationUtils.findAnnotation(method, PermissionIgnore.class);

        if (premissionIgnore == null) {
            if (permission == null) {
                permission = AnnotationUtils.findAnnotation((joinPoint.getTarget().getClass()), Permission.class);
            }

            if (permission != null) {
//                log.debug("ip={} user={} url={}, permission:{}", ip, UserContext.getUser().getUserName(), request.getRequestURI(), permission.value());
//                Assert.isTrue(SystemUtil.hasMenu(UserContext.getUser(), permission.value()),
//                        () -> new ServiceException(BloomErrorEnum.e_0024.getCode()));
                LOGGER.info("ip=[{}] url=[{}], permission:[{}]", ip, request.getRequestURI(), permission.value());
            }
        }
    }

}
